import cache from '../../enum/cache'
import Category from '../../model/category'
import Service from '../../model/service'
import Tim from '../../model/tim'
import { throttle } from '../../utils/utils'
import { setTabBarBadge } from '../../utils/wx'
// pages/home/home.js
const service = new Service()
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		tabs: ['全部服务', '在提供', '正在找'],
		categoryList: [],
		loading: true,
		serviceList: [],
		tabIndex: 0,
		categoryId: 0,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		await this._getServiceList()
		await this._getCategoryList()
		this.setData({
			loading: false,
		})
	},
	onShow() {
		const unreadCount = wx.getStorageSync(cache.UNREAD_COUNT)
		setTabBarBadge(unreadCount)
	},
	async _getServiceList() {
		const serviceList = await service
			.reset()
			.getServiceList(this.data.categoryId, this.data.tabIndex)
		console.log(serviceList)
		this.setData({
			serviceList: serviceList,
		})
	},
	async _getCategoryList() {
		const categoryList = await Category.getCategoryListWithAll()
		this.setData({
			categoryList,
		})
	},
	handleTabChange(event) {
		this.data.tabIndex = event.detail.index
		this._getServiceList()
	},

	handleCategoryChange: throttle(function (event) {
		if (this.data.categoryId === event.currentTarget.dataset.id) {
			return
		}
		this.data.categoryId = event.currentTarget.dataset.id
		this._getServiceList()
	}, 500),
	//服务列表点击事件
	handleSelectService(event) {
		const service = event.target.dataset.service
		wx.navigateTo({
			url:
				'/pages/service-detail/service-detail?service_id=' + service.id,
		})
	},
	//下拉刷新
	async onPullDownRefresh() {
		this._getServiceList()
		wx.stopPullDownRefresh()
	},
	//上拉触底
	async onReachBottom() {
		if (!service.hasMoreData) {
			return
		}
		const serviceList = await service.getServiceList(
			this.data.categoryId,
			this.data.tabIndex
		)
		this.setData({ serviceList })
	},
})
